<?php

namespace app\common\model;

use think\Log;
use think\Model;

class BehaviorRecord extends Model
{
    // 表名
    protected $name = 'behavior_record';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = false;

    protected static function init()
    {
        static::beforeDelete(function ($row) {
            BehaviorRecordDetail::where('record_id', $row->id)->delete();
            BehaviorRecordImage::destroy(['record_id' => $row->id]);
        });
    }

    public function details()
    {
        return $this->hasMany(BehaviorRecordDetail::class, 'record_id');
    }

    public function images()
    {
        return $this->hasMany(BehaviorRecordImage::class, 'record_id');
    }

    public function getJsonDataAttr($value)
    {
        return json_decode($value, true);
    }

    /**
     * 获取点评记录
     *
     * @User ZhenZiHan
     * @Date 2020/3/27
     *
     * @param string $type 类型 BehaviorCategory::CLASSES，BehaviorCategory::STUDENT，BehaviorCategory::DORM
     * @param int $id
     * @param array $behavior_category_type
     * @param string|int $time_type
     * @param int $listRows
     * @return array|\think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getRecords($type, $id, $behavior_category_type, $time_type = "month", $listRows)
    {
        $key = self::getKey($type);
        if (isset($key['error'])) {
            return $key;
        }

        $date = get_time($time_type, true);

        if (!$listRows) {
            $listRows = config('paginate.list_rows');
        }

        $list = BehaviorRecord::with(['details' => function($query) use ($behavior_category_type){
            $query->with('category')->whereIn('behavior_category_type', $behavior_category_type);
        }, 'images'])
            ->where("$key", $id)
            ->whereIn('behavior_category_type', $behavior_category_type)
            ->whereBetween('created_at', [$date['start_time'], $date['end_time']])
            ->field('id,record_user_id,record_username,record_user_group,behavior_category_type,comment,created_at')
            ->order('id', 'desc')
            ->paginate($listRows);

        foreach ($list as $key => $value) {
            $list[$key]['total_score'] = array_sum(array_column($value['details'], 'score'));
        }

        return $list;
    }

    /**
     * 获取图例数据
     *
     * @User ZhenZiHan
     * @Date 2020/4/7
     *
     * @param $type  类型
     * @param $id id
     * @param int $time_type
     * @param bool $group 是否分组
     * @return array|false|int|mixed|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getCharts($type, $id, $time_type = 0, $group = true)
    {
        $key = self::getKey($type);
        if (isset($key['error'])) {
            return $key;
        }

        $ret = BehaviorRecord::alias('record')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
            ->where("record.$key", $id)
            ->where(function ($query) use ($time_type) {
                if ($time_type) {
                    $date = get_time($time_type, true);
                    $query->whereBetween('created_at', [$date['start_time'], $date['end_time']]);
                }
            })
            ->field("detail.behavior_id,detail.behavior_name,detail.behavior_type,sum(detail.score) score")
            ->group("detail.behavior_id,detail.behavior_type")
            ->select();

        if (!$group) {
            return $ret;
        }

        $data = [];
        foreach ($ret as $key => $value) {
            switch ($value['behavior_type']) {
                case Behavior::POSITIVE:
                    $data['positive'][] = $value;
                    break;
                case Behavior::NEGATIVE:
                    $data['negative'][] = $value;
                    break;
            }
        }

        return $data;
    }

    public static function getKey($type)
    {
        switch ($type) {
            case BehaviorCategory::CLASSES:
            case 'classes':
                $key = 'class_id';
                break;
            case BehaviorCategory::STUDENT:
            case 'student':
                $key = 'student_id';
                break;
            case BehaviorCategory::DORM:
            case 'dorm':
                $key = 'dorm_id';
                break;
            default:
                return [
                    'error' => 1,
                    'msg' => '类型错误'
                ];
                break;
        }

        return $key;
    }
}
